package cn.tesla_iot.bluetoothchat;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import cn.tesla_iot.chat.video.monitor.R;

public class DeviceListActivity extends Activity {

	private TextView tvDeviceListPairedDeviceTitle, tvDeviceListNewDeviceTitle;
	private ListView lvDeviceListPairedDevice, lvDeviceListNewDevice;
	private Button btnDeviceListScan;

	private BluetoothAdapter bluetoothAdapter;
	//private ArrayAdapter<String> pairedDevicesArrayAdapter;
	//private ArrayAdapter<String> newDevicesArrayAdapter;
	private List<BluetoothDevice> pairedDevicesArrayAdapter;
	private List<BluetoothDevice> newDevicesArrayAdapter;

	public static String DEVICE_ADDRESS = "deviceAddress";


	private List<Map<String, String>> pairedList;
	private List<Map<String, String>> list;
	SimpleAdapter pairedAdapter;
	SimpleAdapter adapter;

	public void setDiscoverableTimeout(BluetoothAdapter adapter, int timeout) {
		try {
			Method setDiscoverableTimeout = BluetoothAdapter.class.getMethod("setDiscoverableTimeout", int.class);
			setDiscoverableTimeout.setAccessible(true);
			Method setScanMode = BluetoothAdapter.class.getMethod("setScanMode", int.class,int.class);
			setScanMode.setAccessible(true);

			setDiscoverableTimeout.invoke(adapter, timeout);
			setScanMode.invoke(adapter, BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE,timeout);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
		setContentView(R.layout.device_list);

		//setResult(Activity.RESULT_CANCELED);

		getWidgetReferences();
		bindEventHandler();
		initializeValues();

		if (!blueisenable()) {
			Intent enabler = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
			startActivityForResult(enabler, 1);
			return ;
		} else {
			startscan();
		}
	}

	private void getWidgetReferences() {
		tvDeviceListPairedDeviceTitle = (TextView) findViewById(R.id.tvDeviceListPairedDeviceTitle);
		tvDeviceListNewDeviceTitle = (TextView) findViewById(R.id.tvDeviceListNewDeviceTitle);

		lvDeviceListPairedDevice = (ListView) findViewById(R.id.lvDeviceListPairedDevice);
		lvDeviceListNewDevice = (ListView) findViewById(R.id.lvDeviceListNewDevice);

		btnDeviceListScan = (Button) findViewById(R.id.btnDeviceListScan);

	}


	public boolean blueisenable() {
		if (bluetoothAdapter.isEnabled()) {
			return true;
		} else {
			return false;
		}
	}

	void showPairedDevice() {

		pairedList.clear();

		pairedDevicesArrayAdapter.clear();
		pairedAdapter.notifyDataSetChanged();
		Set<BluetoothDevice> pairedDevices = bluetoothAdapter
				.getBondedDevices();
		// If there are paired devices, add each one to the ArrayAdapter
		if (pairedDevices.size() > 0) {
			tvDeviceListPairedDeviceTitle.setVisibility(View.VISIBLE);
			for (BluetoothDevice device : pairedDevices) {
				//pairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
				pairedDevicesArrayAdapter.add(device);


				Map<String, String> map = new HashMap<String, String>();
				map.put("deviceName", device.getName() + ":" + device.getAddress());
				map.put("statue", "已配对");

				pairedList.add(map);

				pairedAdapter.notifyDataSetChanged();
			}
		} else {
			//String noDevices = getResources().getText(R.string.none_paired).toString();
			//pairedDevicesArrayAdapter.add(noDevices);
		}
	}

	private void bindEventHandler() {
		lvDeviceListPairedDevice.setOnItemClickListener(mPairedDeviceClickListener);
		lvDeviceListNewDevice.setOnItemClickListener(mDeviceClickListener);

		btnDeviceListScan.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {


				if (!blueisenable()) {
					Intent enabler = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
					startActivityForResult(enabler, 1);
					return ;
				} else {
					startscan();
				}
			}
		});
	}

	void startscan(){
		showPairedDevice();

		newDevicesArrayAdapter.clear();
		adapter.notifyDataSetChanged();
		startDiscovery();
		btnDeviceListScan.setVisibility(View.GONE);
	}

	private void initializeValues() {
		//pairedDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);
		//newDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);
		//pairedDevicesArrayAdapter = new ArrayList<BluetoothDevice>(this, R.layout.devices);
		//newDevicesArrayAdapter = new ArrayList<BluetoothDevice>(this, R.layout.devices);
		pairedDevicesArrayAdapter = new ArrayList<BluetoothDevice>();
		newDevicesArrayAdapter = new ArrayList<BluetoothDevice>();
		Map<String, String> map = new HashMap<>();


		list = new ArrayList<>();
		pairedList = new ArrayList<>();

		//list.add(map);
		pairedAdapter = new SimpleAdapter(DeviceListActivity.this, pairedList, R.layout.devices, new String[]{"deviceName", "statue"}, new int[]{R.id.devicename, R.id.statue});
		lvDeviceListPairedDevice.setAdapter(pairedAdapter);
		adapter = new SimpleAdapter(DeviceListActivity.this, list, R.layout.devices, new String[]{"deviceName", "statue"}, new int[]{R.id.devicename, R.id.statue});
		lvDeviceListNewDevice.setAdapter(adapter);

		// Register for broadcasts when a device is discovered
		IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
		registerReceiver(discoveryFinishReceiver, filter);

		// Register for broadcasts when discovery has finished
		filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
		registerReceiver(discoveryFinishReceiver, filter);

		bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

		setDiscoverableTimeout(bluetoothAdapter, 300);

		showPairedDevice();
	}

	private void startDiscovery() {

		Intent enabler = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
		startActivity(enabler);

		setDiscoverableTimeout(bluetoothAdapter, 300);

		setProgressBarIndeterminateVisibility(true);
		setTitle(R.string.scanning);

		tvDeviceListNewDeviceTitle.setVisibility(View.VISIBLE);

		if (bluetoothAdapter.isDiscovering()) {
			bluetoothAdapter.cancelDiscovery();
		}

		bluetoothAdapter.startDiscovery();
	}

	private OnItemClickListener mPairedDeviceClickListener = new OnItemClickListener() {
		public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
			bluetoothAdapter.cancelDiscovery();

			//String info = ((TextView) v).getText().toString();
			//String address = info.substring(info.length() - 17);


			BluetoothDevice device = pairedDevicesArrayAdapter.get(arg2);
			String address = device.getAddress();

			//Intent intent = new Intent(DeviceListActivity.this, ChatActivity.class);
			Intent intent = new Intent(DeviceListActivity.this, CommActivity.class);
			intent.putExtra(DEVICE_ADDRESS, address);



			startActivity(intent);

			//setResult(Activity.RESULT_OK, intent);
			//finish();
		}
	};



	private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
		public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
			bluetoothAdapter.cancelDiscovery();


			//BluetoothDevice device = listdevice.get(position);
			//device.createBond();

			/*
			String info = ((TextView) view).getText().toString();
			String address = info.substring(info.length() - 17);

			//Intent intent = new Intent(DeviceListActivity.this, ChatActivity.class);
			Intent intent = new Intent(DeviceListActivity.this, CommActivity.class);
			intent.putExtra(DEVICE_ADDRESS, address);



			startActivity(intent);
*/
			BluetoothDevice device = newDevicesArrayAdapter.get(position);
			device.createBond();
		}
	};

	private final BroadcastReceiver discoveryFinishReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();

			if (BluetoothDevice.ACTION_FOUND.equals(action)) {
				BluetoothDevice device = intent
						.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
				if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
					//newDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
					newDevicesArrayAdapter.add(device);


					Map<String, String> map = new HashMap<String, String>();
					map.put("deviceName", device.getName() + ":" + device.getAddress());
					map.put("statue", "未配对");

					list.add(map);

					adapter.notifyDataSetChanged();

				}
			} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED
					.equals(action)) {
				setProgressBarIndeterminateVisibility(false);
				setTitle(R.string.select_device);
				if (newDevicesArrayAdapter.size() == 0) {
					//String noDevices = getResources().getText(R.string.none_found).toString();
					//newDevicesArrayAdapter.add(noDevices);
				}
			}
		}
	};

	@Override
	protected void onDestroy() {
		super.onDestroy();

		if (bluetoothAdapter != null) {
			bluetoothAdapter.cancelDiscovery();
		}
		this.unregisterReceiver(discoveryFinishReceiver);
	}

}
